import Cookie from 'js-cookie'
import jwtDecode from 'jwt-decode'

export const setToken = (name, data) => {
    if (process.SERVER_BUILD) return;
    window.localStorage.setItem(name, data);
    Cookie.set(name, data)
};

//获取url最后一个/后面的字符串
export const getLastParam = (url) => {
    url = url.substring(url.lastIndexOf("/"));
    return url;
};


export const unsetToken = (name) => {
    if (process.SERVER_BUILD) return;
    window.localStorage.removeItem(name);
    Cookie.remove(name);
    window.localStorage.setItem('logout', Date.now())
};

export const getUserFromCookie = (req, name) => {
    if (!req.headers.cookie) return;
    const Cookie = req.headers.cookie.split(';').find(c => c.trim().startsWith(name + '='));
    if (!Cookie) return;
    const cookie = Cookie.split('=')[1];
    return cookie
};

export const getCookie = (name) => {
    if (process.SERVER_BUILD) return;
    return Cookie.get(name);
};

export const getTime = (option) => {
    var date = new Date();
    var Year = date.getFullYear();
    var Month = date.getMonth() + 1;
    var Day = date.getDate();
    switch (option) {
        case 0:
            return Year;
            break;
        case 1:
            return Month;
            break;
        case 2:
            return Day;
            break;
    }
};
export const getDate = (date, boolean) => {
    var Year = date.getFullYear();
    var Month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var Day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    if (boolean == true) {
        var Hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        var Minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        var Second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return (Year + '-' + Month + '-' + Day + ' ' + Hour + ':' + Minute + ':' + Second)
    } else {
        return (Year + '-' + Month + '-' + Day)
    }

};

/*根据日期字符串，返回Date对象,兼容safari*/
export const returnDate = (dateTimeString) => {
    if (typeof(dateTimeString) != "string") {
        return new Date(dateTimeString)
    }
    var datetime;
    if (isNaN(Date.parse(dateTimeString))) {
        datetime = new Date(Date.parse(dateTimeString.replace(/-/g, '/').replace(/T/g, '')));
    } else {
        datetime = new Date(Date.parse(dateTimeString))
    }
    return datetime
};

export const getYesterday = (time) => {
    var date = time || new Date(),
        timestamp,
        newDate;
    if (!(date instanceof Date)) {
        date = new Date(date.replace(/-/g, '/'));
    }
    timestamp = date.getTime();
    newDate = new Date(timestamp - 1 * 24 * 3600 * 1000);
    return [newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate()].join('-');
};

export const getSevenDaysBefore = (time) => {
    var date = time || new Date(),
        timestamp,
        newDate;
    if (!(date instanceof Date)) {
        date = new Date(date.replace(/-/g, '/'));
    }
    timestamp = date.getTime();
    newDate = new Date(timestamp - 7 * 24 * 3600 * 1000);
    return [newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate()].join('-');
}

export const browserType = (from) => {
    var explorer = from.toLowerCase();
    //ie
    var isIe8 = false;
    if (explorer.indexOf("msie") >= 0) {
        var ver = explorer.match(/msie ([\d.]+)/)[1];
        if (ver <= '9.0') {
            isIe8 = true;
        }
    }
    return isIe8;
};

export const getLevel = (level) => {
    switch (level) {
        case '0类（新开客户）':
            return '337';
            break;
        case '1类（可沟通）':
            return '338';
            break;
        case '2类（有迫切动机需求）':
            return '339';
            break;
        case '3类（认可价格和服务）':
            return '340';
            break;
        case '4类（7天内付款）':
            return '341';
            break;
        case '5类（24小时内办理）':
            return '342';
            break;
        case '6类（毁单）':
            return '343';
            break;
        case '7类（3类降下来的客户）':
            return '344';
            break;
        case '8类（已签单客户）':
            return '345';
            break;
    }
};

export const getLevelName = (id) => {
    switch (id) {
        case 337:
            return '0类';
            break;
        case 338:
            return '1类';
            break;
        case 339:
            return '2类';
            break;
        case 340:
            return '3类';
            break;
        case 341:
            return '4类';
            break;
        case 342:
            return '5类';
            break;
        case 343:
            return '6类';
            break;
        case 344:
            return '7类';
            break;
        case 345:
            return '8类';
            break;
    }
};
export const getLevelNames = (id) => {
    switch (id) {
        case 0:
            return '0类';
            break;
        case 1:
            return '1类';
            break;
        case 2:
            return '2类';
            break;
        case 3:
            return '3类';
            break;
        case 6:
            return '6类';
            break;
        
    }
};

export const getLevelBrand = (id) => {
    switch (level) {
        case '0类（未开始操作客户）':
            return '0';
            break;
        case '1类（常规客户）':
            return '1';
            break;
        case '2类（接触频繁客户）':
            return '2';
            break;
        case '3类（重点客户）':
            return '3';
            break;
        case '6类（断约客户）':
            return '6';
            break;
    }
};

export const getArraySub = (array, element) => {
    var count = '';
    for (var i = 0; i < array.length; i++) {
        if (element == array[i]) {
            count = i;
        }
    }
    return count;
};

export const validTel = (phone) => {
    var pattern = /(^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$)|(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
    if (pattern.test(phone)) {
        return true;
    } else {
        return false;
    }
};
export const validFixedTel = (tel) => {
    var reg = /^0\d{2,3}-\d{7,8}(-\d{1,6})?$/;
    if (reg.test(tel)) {
        return true;
    } else {
        return false;
    }
}


export const validEmail = (email) => {
    var pattern = /^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.){1,4}[a-z]{2,3}$/;
    if (pattern.test(email)) {
        return true;
    } else {
        return false;
    }
};

export const checkeurl = (url) => {
    var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
        + "|" // 允许IP和DOMAIN（域名）
        + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // 端口- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
    var re = new RegExp(strRegex);
    if (re.test(url)) {
        return (true);
    } else {
        return (false);
    }
};

export const checkQQ = (qq) => {
    var reQQ = /^[1-9]\d{4,9}$/;
    if (!reQQ.test(qq)) {
        return false;
    } else {
        return true;
    }
}

export const base64Decode = (input) => {
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1,
        chr2,
        chr3;
    var enc1,
        enc2,
        enc3,
        enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
        enc1 = _keyStr.indexOf(input.charAt(i++));
        enc2 = _keyStr.indexOf(input.charAt(i++));
        enc3 = _keyStr.indexOf(input.charAt(i++));
        enc4 = _keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    return output;
}

export const removeEmptyKey = (obj) => {
    let con = {}
    for (let key in obj) {
        if (obj.hasOwnProperty(key) && obj[key]) {
            con[key] = obj[key]
        }
    }
    return con;
}


//数组去重
export const uniqueArr = (array) => {
    var r = [];
    for (var i = 0, l = array.length; i < l; i++) {
        for (var j = i + 1; j < l; j++)
            if (array[i] === array[j]) j = ++i;
        r.push(array[i]);
    }
    return r;
}